package com.example.communicate;

import java.io.IOException;
import java.net.Socket;

public class MyServerSocket {  // 重命名类，避免与java.net.ServerSocket冲突
    private java.net.ServerSocket serverSocket;
    private int port;

    // 构造方法，初始化服务器端口
    public MyServerSocket(int port) {
        this.port = port;
    }

    // 启动服务器，开始监听客户端连接
    public void startServer() {
        try {
            serverSocket = new java.net.ServerSocket(port);
            System.out.println("服务器启动，监听端口：" + port);

            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("客户端连接：" + clientSocket.getInetAddress());
                // 处理客户端连接（此处可以使用线程池处理多个客户端）
                new Thread(new ClientHandler(clientSocket)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 内部类，用于处理客户端请求
    private static class ClientHandler implements Runnable {
        private Socket clientSocket;

        public ClientHandler(Socket clientSocket) {
            this.clientSocket = clientSocket;
        }

        @Override
        public void run() {
            // 处理客户端请求逻辑
            try {
                byte[] buffer = new byte[1024];
                int length = clientSocket.getInputStream().read(buffer);
                String receivedData = new String(buffer, 0, length);
                System.out.println("接收到客户端数据：" + receivedData);
                // 回应客户端
                clientSocket.getOutputStream().write("已收到".getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    clientSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
